package com.gugee.tiktok.web.controller;

import com.gugee.common.web.config.BaseController;
import com.gugee.common.web.system.user.model.User;
import com.gugee.common.web.system.user.repository.UserRoleRepository;
import com.xiguaji.boot.toolkit.HttpUtil;
import com.xiguaji.boot.toolkit.JsonUtil;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;

@RequestMapping("/v1/")
public class TikTokBaseController extends BaseController {

    @Autowired
    UserRoleRepository userRoleRepository;

    protected User getUser(){
        String token = HttpUtil.getCookie(authorized);

        if(StringUtils.isEmpty(token)){
            return null;
        }
        return JsonUtil.jsonParse(User.class,JsonUtil.parseJson(jwtUtil.getJwtUser(token).getUser()));
    }


    protected long getRoleId(){
        long roleId = 1;
        User user = getUser();
        val userRoleOptional = userRoleRepository.findTop1ByUserIdAndExpireTimeGreaterThanEqualOrderByRoleIdDesc(user.getParentId() == 0 ?user.getId():user.getParentId(), new Date());

        if(userRoleOptional.isPresent()){
            roleId = userRoleOptional.get().getRoleId();
        }
        return roleId;
    }
}
